package com.me.mysqladmin.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.sql.RowSet;

import org.springframework.stereotype.Repository;

import com.me.mysqladmin.dao.TableStatusDAO;
import com.me.mysqladmin.entity.TableName;
import com.me.mysqladmin.entity.TableStatus;
import com.me.mysqladmin.util.RowSetUtil;

@Repository("tableStatusDAO")
public class TableStatusDAOImpl extends BaseDAOImpl<TableStatus> implements TableStatusDAO {
	// 集中定义SQL语句
	private static String QUERY_BY_DB = "SHOW TABLE STATUS FROM ";
	private static String DROP_TABLE = "DROP TABLE IF EXISTS ";
	private static String RENAME_TABLE = "RENAME TABLE ";
	
	/**
	 * 查询指定数据库下的表信息（实体集表示）
	 */
	@Override
	public List<TableStatus> queryByDb(String dbName) {
		try {
			return query(QUERY_BY_DB + dbName);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}
	
	/**
	 * 查询指定数据库下的表信息（listMap表示）
	 */
	@Override
	public List<Map<String, Object>> queryMapByDb(String dbName) {
		try {
			return queryMap(QUERY_BY_DB + dbName);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}
	
	/**
	 * 查询指定数据库下的表名称
	 */
	@Override
	public List<String> queryTableNames(String dbName) {
		List<String> tblNames = new ArrayList<>();
		List<TableStatus> list = queryByDb(dbName);
		for(TableStatus tableStatus : list){
			tblNames.add(tableStatus.getTable_name());
		}
		return tblNames;
	}

	@Override
	protected List<TableStatus> toEntities(RowSet rs) {
		return RowSetUtil.toEntiyList(rs, TableStatus.class);
	}

	/**
	 * 删除指定数据库下的一张表
	 */
	@Override
	public Integer dropTable(TableStatus tableStatus) throws SQLException {
		String databaseName = tableStatus.getDatabaseName();
		String tableName = tableStatus.getTable_name();
		return baseDML(DROP_TABLE + databaseName + "." + tableName);
	}

	/**
	 * 更新表名
	 */
	@Override
	public void renameTable(TableName tableName) throws SQLException {
		String oldLoc = tableName.getDatabaseName() + "." + tableName.getOldName();
		String newLoc = tableName.getDatabaseName() + "." + tableName.getNewName();
		baseDML(RENAME_TABLE + oldLoc + " to " + newLoc);
	}
}
